<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import ExportButton from './ExportButton.vue'
import * as BasicApi from '@/api'
import { objectToQueryParams } from '@/utils/objectToQuery'
import { Plus, Select, Search, Refresh, Upload } from '@element-plus/icons-vue'

import { useMessage } from '@/hooks/useMessage'
import eventBus from '@/libs/eventBus'
const message = useMessage()

const props = defineProps(['partParams'])

const formQuery = {
  type: '',
  key: '',
  keyType: 'text',
  value: '',
  date: '',
  pageNo: 1,
  pageSize: 15
}
const queryParams = reactive({
  type: '',
  key: '',
  keyType: 'text',
  value: '',
  date: '',
  list: [],
  pageNo: 1,
  pageSize: 15
})

const emit = defineEmits(['getData', 'getTableData', 'handlePush', 'openModal'])

//日期控件
const date = ref()
const dateRange = ref()
const dateTimeRange = ref()
//下拉框控件
const select = ref()
const multiSelect = ref()

//查询
function handleQuery() {
  //去除输入框内的空格
  queryParams.value = queryParams.value.trim()
  const temp = JSON.parse(JSON.stringify(queryParams))
  const post = {
    ...temp,
    ...props.partParams
  }
  //处理日期
  if (dateRange.value || dateTimeRange.value) {
    const startDateStr = queryParams.date[0]
    const endDateStr = queryParams.date[1]
    post.startDate = startDateStr
    post.endDate = endDateStr
    delete post.date
  }
  if (select.value) {
    post.value = queryParams.value
    delete post.list
  }
  //处理多选下拉框
  if (multiSelect.value) {
    delete post.value
    //将[1,2]转为[{Value: 1},{Value: 2}]
    const valArr = queryParams.list
    post.list =
      valArr.length &&
      valArr.map((item) => {
        return {
          Value: item
        }
      })
    console.log(`output->`, '处理多选下拉框')
  }
  emit('getData', post)
}

//重置
function handleReset() {
  //将表单置空
  Object.assign(queryParams, formQuery)
  //清空值的下拉框数据
  valueList.value = []
}

//获取类型
const typeList = ref<any[]>([])
const getTypeList = async () => {
  const params = {
    ...props.partParams,
    operType: 'GetType'
  }
  const inputStr = objectToQueryParams(params)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  typeList.value = data.listInfo || []
}

//获取条件
const keyList = ref<any[]>([])
const getKeyList = async () => {
  const params = {
    ...props.partParams,
    type: queryParams.type,
    operType: 'GetKey'
  }
  const inputStr = objectToQueryParams(params)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  keyList.value = data.listInfo || []
}

function changeType() {
  queryParams.key = ''
  keyList.value = []
  queryParams.keyType = ''
  queryParams.value = ''
  valueList.value = []
  if (!queryParams.type) {
    return
  }
  getKeyList()
}

function changeKey() {
  queryParams.value = ''
  if (!queryParams.key) {
    return
  }
  //先获取Key的Type
  const result = keyList.value.filter((item) => item.Value === queryParams.key)
  queryParams.keyType = (result.length && result[0].ValueType) || 'text'
  //如果Type为select则要去获取下拉框数据
  if (queryParams.keyType == 'Select') {
    getValueList()
  }
}

//获取值
const valueList = ref<any[]>([])
const getValueList = async () => {
  const post = {
    ...props.partParams,
    type: queryParams.type,
    key: queryParams.key,
    operType: 'GetValue'
  }
  const inputStr = objectToQueryParams(post)
  const result = (await BasicApi.Query({ inputStr })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  valueList.value = data.listInfo || []
}

//是否有类型
const isShowType = ref(false)
//获取筛选项
const filterInfo = ref<any[]>([]) // 列表的数据
const buttonInfo = ref<any[]>([])

const getFilter = async () => {
  const post = {
    groupName: props.partParams.groupName,
    jobType: props.partParams.jobType,
    operType: 'GetPageInfo'
  }
  const inputStr = objectToQueryParams(post)
  const result = (await BasicApi.Query({ inputStr, jsonData: '' })) as any
  const { code, msg, data } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  const { filter, operate } = data.pageInfo
  filterInfo.value = filter.filter((item: any) => item.type !== 'Button')
  const tempInfo = filter.filter((item: any) => item.type === 'Button')
  buttonInfo.value = tempInfo.concat(operate)
  const res = filter.filter((item: any) => item.value == 'Type')
  isShowType.value = res.length ? true : false
  //将result传递给table 1.获取表头信息fieldInfo 2.获取行操作按钮
  emit('getTableData', data)
}

//新增
function handleAdd() {
  emit('openModal')
}

onMounted(async () => {
  await getFilter()
  isShowType.value ? getTypeList() : getKeyList()
})
</script>
<template>
  <!-- 搜索工作栏 -->
  <el-form
    class="-mb-15px my-form"
    :model="queryParams"
    ref="queryFormRef"
    :inline="true"
    label-width="60px"
  >
    <template v-for="(item, index) in filterInfo" :key="index">
      <el-form-item v-if="item.value == 'Type'" :label="item.label">
        <el-select
          v-model="queryParams.type"
          filterable
          clearable
          placeholder="请选择"
          style="width: 220px"
          @change="changeType"
        >
          <el-option
            v-for="item in typeList"
            :key="item.Label"
            :label="item.Label"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="item.value == 'Key'" :label="item.label">
        <el-select
          v-model="queryParams.key"
          filterable
          clearable
          placeholder="请选择"
          style="width: 220px"
          @change="changeKey"
        >
          <el-option
            v-for="item in keyList"
            :key="item.Label"
            :label="item.Label"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="item.value == 'Value'" :label="item.label">
        <template v-if="queryParams.keyType == 'Select'">
          <el-select
            ref="select"
            v-model="queryParams.value"
            filterable
            clearable
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in valueList"
              :key="item.Value"
              :label="item.Label"
              :value="item.Value"
            />
          </el-select>
        </template>
        <template v-else-if="queryParams.keyType == 'MultiSelect'">
          <el-select
            ref="multiSelect"
            v-model="queryParams.list"
            multiple
            collapse-tags
            collapse-tags-tooltip
            filterable
            clearable
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in valueList"
              :key="item.Value"
              :label="item.Label"
              :value="item.Value"
            />
          </el-select>
        </template>
        <template v-else>
          <el-input
            v-model="queryParams.value"
            placeholder="请输入"
            clearable
            style="width: 220px"
          />
        </template>
      </el-form-item>
      <el-form-item v-if="item.value == 'Date'" :label="item.label">
        <el-date-picker
          v-if="item.type == 'Date'"
          ref="date"
          v-model="queryParams.date"
          placeholder="请输入"
          type="date"
          value-format="YYYY-MM-DD"
        />
        <el-date-picker
          v-if="item.type == 'DateRange'"
          ref="dateRange"
          v-model="queryParams.date"
          placeholder="请输入"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-date-picker
          v-if="item.type == 'DateTimeRange'"
          ref="dateTimeRange"
          v-model="queryParams.date"
          placeholder="请输入"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
    </template>
    <el-form-item>
      <template v-for="(item, index) in buttonInfo" :key="index">
        <el-button type="primary" :icon="Search" v-if="item.value == 'Search'" @click="handleQuery">
          {{ item.label }}</el-button
        >
        <el-button v-if="item.value == 'Reset'" :icon="Refresh" @click="handleReset">
          {{ item.label }}</el-button
        >
        <el-button
          type="success"
          :icon="Select"
          v-if="item.value == 'POReceive'"
          @click="$emit('handlePush', queryParams)"
        >
          {{ item.label }}</el-button
        >
        <template v-if="item.value == 'Export'">
          <ExportButton :label="item.label" :partParams="partParams" />
        </template>
        <el-button
          v-if="item.value == 'Add'"
          class="btn-add"
          type="success"
          :icon="Plus"
          plain
          @click="handleAdd"
          >{{ item.label }}
        </el-button>
        <el-button
          v-if="item.value == 'Upload'"
          class="btn-add"
          type="warning"
          :icon="Upload"
          plain
        >
          {{ item.label }}
        </el-button>
      </template>
    </el-form-item>
  </el-form>
</template>
